import React from 'react';
import { TreeType, DicVals } from 'orgc-manage';
import { Input, Modal, Table, Row, Col, message, Form, Button, Tag } from 'antd';
import _ from 'lodash';
import { xhrPostJson, api } from '@/services';
import './index.less';
import AsyncTree from '../async-tree';
import { CheckOutlined, RollbackOutlined, SearchOutlined, UndoOutlined } from '@ant-design/icons';
import { formatMessage } from '@/utils/i18n-transform';
// TODO: 需要根据根节点处理
const SELECT_NODE = {
  isRoot: true,
  name: formatMessage({ id: 'org.orgStrc' }),
  nodeName: formatMessage({ id: 'org.orgStrc' }),
  id: '0',
  parentId: '0',
  code: '',
  nodeType: 'COMPANY', isLeaf: false, typeName: '', children: null,
}
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};
const BASEPAGINATION = {
  pageNo: 1,
  pageSize: 5,
  total: 1,
  current: 1,
};
interface TablePagination {
  pageNo: number;
  pageSize: number;
  current: number;
  total: number;
}
interface ComponentState {
  treeData: TreeType[];
  selectNode: TreeType | any;
  changeTree: boolean;
  dicVals: DicVals;
  visible: boolean;
  showValue: string;
  listLoading: boolean;
  tablePagination: TablePagination;
  personData: any[];
  selectedRowKeys: any[];
  selectedRows: any[];
  recValue: any;
  selectedData: any;
  selecteKeys: any;
}
// enum Type {
//   'radio' = "radio",
//   'checkbox' = "checkbox"
// }
interface ComponentProps {
  value?: any;
  rowKey?: any;
  selectType?: string;
  inputDefaultValue?: string;
  onChange?: (values: any, data?: any) => void;
  showValueKey?: string;
  initNull?: boolean;
  parentIds?: any[];
}
class OrgEmpSelect extends React.Component<ComponentProps, ComponentState> {
  formRef: any = React.createRef();
  constructor(props: any) {
    super(props);
    this.state = {
      recValue: '', // 接收的value
      treeData: [],
      showValue: '',
      visible: false,
      selectNode: SELECT_NODE,
      changeTree: false,
      dicVals: {},
      listLoading: false,
      selectedRowKeys: [],
      selectedRows: [],
      personData: [],
      selectedData: [],
      selecteKeys: [],
      tablePagination: {
        ...BASEPAGINATION,
      },
    };
  }

  // 初始化
  componentDidMount() {
    const { selectType, inputDefaultValue, value, rowKey = 'id' } = this.props;
    // 如果初始化
    if (inputDefaultValue && value) {
      let selectedData: any[] = [];
      let selecteKeys: any[] = [];
      if (selectType === 'checkbox') {
        // 多选
        const names = inputDefaultValue.split(',');
        // 可初始化
        selecteKeys = value.split(',');
        selecteKeys.map((key: any, index: any) => {
          selectedData.push({
            [rowKey]: key,
            name: names[index],
          });
        });
      } else {
        // 单选
        selecteKeys = [value];
        selectedData = [
          {
            [rowKey]: value,
            name: inputDefaultValue,
          },
        ];
      }

      this.setState({
        selecteKeys,
        selectedData,
        selectedRowKeys: [...selecteKeys],
        selectedRows: [...selectedData],
        recValue: inputDefaultValue,
      });
    }
  }

  // 后一步初始化
  UNSAFE_componentWillReceiveProps(nextProps) {
    const { selectType, inputDefaultValue, value, rowKey = 'id' } = nextProps;
    const { selecteKeys: skeYS } = this.state;
    // 如果初始化
    if (inputDefaultValue && skeYS.length === 0) {
      let selectedData: any[] = [];
      let selecteKeys: any[] = [];
      if (selectType === 'checkbox') {
        // 多选
        const names = inputDefaultValue.split(',');
        // 可初始化
        selecteKeys = value.split(',');
        selecteKeys.map((key: any, index: any) => {
          selectedData.push({
            [rowKey]: key,
            name: names[index],
          });
        });
      } else {
        // 单选
        selecteKeys = [value];
        selectedData = [
          {
            [rowKey]: value,
            name: inputDefaultValue,
          },
        ];
      }

      this.setState({
        selecteKeys,
        selectedData,
        selectedRowKeys: [...selecteKeys],
        selectedRows: [...selectedData],
        recValue: inputDefaultValue,
      });
    }
  }

  // 树被选中操作
  treeNodeClick = (selectNode: TreeType) => {
    // 查询当前节点下的人员
    if (!_.isEqual(selectNode, this.state.selectNode)) {
      if (selectNode.nodeType === '' && !selectNode.name) {
        return;
      }
      this.setState(
        {
          selectNode,
        },
        () => {
          this.resetPagination(this.getTableList);
        },
      );
    }
  };

  loading = () => {
    this.setState({
      listLoading: !this.state.listLoading,
    });
  };

  formatData = (data: any[]) => {
    return data;
    if (data) {
      return data.filter((item: any) => item.type === 'EMPLOYEE');
    }
    return [];
  };

  // 获取tableList
  getTableList = (search = {}) => {
    this.loading();
    const { nodeType, code } = this.state.selectNode;
    const { pageNo, pageSize } = this.state.tablePagination;
    const obj: any = {
      pageNo,
      pageSize,
      queryKeys: {
        userOrgs: [code],
        pageCode: "USERMGMT_L",
        status: "ENABLE",
        ...search,
      }
    };
    // 改动 处理新的接口参数--> 未选中根节点时删除 parentCode
    if (code === '' || nodeType === '') {
      delete obj.parentCode;
    }
    xhrPostJson('/sym/user/page', { ...obj })
      .then((res: any) => {
        if (res.success) {
          const personData: any = this.formatData(res.result.content);
          this.setState({
            personData,
            tablePagination: {
              ...this.state.tablePagination,
              pageNo: ++res.result.pageNo,
              pageSize: res.result.pageSize ?? 5,
              total: res.result.totalElements,
            },
          });
        }
      })
      .finally(() => {
        this.loading();
      });
  };

  changeTreeData = () => { };

  showModal = () => {
    this.setState({
      visible: true,
    });
  };

  hideModal = () => {
    this.setState({
      visible: false,
      selectNode: SELECT_NODE,
      // selectedRowKeys: [],
      // selectedRows: []
    });
  };
  // table 选择

  handleRowSelect = (selectedRowKeys: any, selectedRows: any) => {
    const { rowKey = 'id' } = this.props;
    const { selectedRows: cSelectedRows } = this.state;
    // 当前的 数据，和选择后的数据，通过 selectedRowKeys 来过滤;
    // 存在不同 就是有初始化的值；
    const uniq = _.uniqBy(cSelectedRows.concat(selectedRows), rowKey);
    // merge 之后以 selectedRowKeys 最后来处理数组
    const findalData: any[] = selectedRowKeys.map((key: any) => {
      const index = _.findIndex(uniq, o => o[rowKey] == key);
      return uniq[index];
    });
    // 这里需要处理 --》》》
    this.setState({
      selectedRowKeys,
      selectedRows: findalData,
    });
  };

  // 数据change
  handleChange = () => {
    const { onChange, showValueKey } = this.props;
    const { selectedRows, selectedRowKeys } = this.state;
    if (selectedRows.length > 0) {
      // 确认选择保存数据到state
      this.setState({
        selectedData: [...selectedRows],
        selecteKeys: [...selectedRowKeys],
        // showValue: selectedRows.map((item) => {
        //   return showValueKey ? item[showValueKey] || item.name : item.name
        // }).join(',')
      });
      this.hideModal();
      this.setState(
        {
          recValue: selectedRowKeys.join(','),
        },
        () => {
          onChange && onChange(selectedRowKeys.join(','), [...selectedRows]);
        },
      );
    } else {
      message.error('请选择人员');
    }
  };

  componentWillReceiveProps(nextProps: any) {
    const { recValue } = this.state;
    if (!recValue && nextProps.value) {
      const { selectType, inputDefaultValue, value, rowKey = 'id' }: any = this.props;
      // 如果初始化
      let selectedData: any[] = [];
      let selecteKeys: any[] = [];
      if (selectType === 'checkbox') {
        // 多选
        const names = (inputDefaultValue && inputDefaultValue.split(',')) || [];
        // 可初始化
        selecteKeys = (value && value.split(',')) || [];
        selecteKeys.map((key: any, index: any) => {
          selectedData.push({
            [rowKey]: key,
            name: names[index],
          });
        });
      } else {
        // 单选
        selecteKeys = [value];
        selectedData = [
          {
            [rowKey]: value,
            name: inputDefaultValue,
          },
        ];
      }

      this.setState({
        selecteKeys,
        selectedData,
        selectedRowKeys: [...selecteKeys],
        selectedRows: [...selectedData],
      });
    }

    // 新增重置逻辑
    if (!nextProps.value) {
      this.setState({
        selecteKeys: [],
        selectedData: [],
        selectedRowKeys: [],
        selectedRows: [],
      });
    }

    // 接收FORM组件传回的值
    this.setState({
      recValue: nextProps.value,
    });
    // 初始化显示默认值
    if (nextProps.defaultShow && nextProps.defaultShow !== this.state.showValue) {
      this.setState({
        showValue: nextProps.defaultShow,
      });
    }
    // 清空 操作
    if (!nextProps.value && this.state.showValue) {
      this.setState({
        selecteKeys: [],
        selectedData: [],
        selectedRowKeys: [],
        selectedRows: [],
        recValue: '',
      });
    }
  }

  resetPagination = (cb: any) => {
    this.setState(
      {
        tablePagination: {
          ...BASEPAGINATION,
        },
      },
      () => {
        cb && cb();
      },
    );
  };

  // table 查询
  handleSearch = () => {
    this.formRef.current.validateFields().then((values: any) => {
      this.resetPagination(() => this.getTableList(values));
    });
  };

  // 分页查询
  handlePaginationChange = (pageNo: any, pageSize: any) => {
    this.setState(
      {
        tablePagination: {
          ...this.state.tablePagination,
          current: pageNo,
          pageNo,
          pageSize
        },
      },
      () => {
        this.formRef.current.validateFields().then((valuse: any) => {

          this.getTableList(valuse);
        });
      },
    );
  };

  // 初始化 labels
  getLables = () => { };

  //
  handleRmTag = (index: any) => {
    const { selectedRowKeys, selectedRows, selectedData, selecteKeys } = this.state;
    selectedRowKeys.splice(index, 1);
    selectedRows.splice(index, 1);
    selectedData.splice(index, 1);
    selecteKeys.splice(index, 1);
    this.setState(
      {
        selectedRowKeys,
        selectedRows,
        selectedData,
        selecteKeys,
      },
      () => {
        const { onChange } = this.props;
        onChange && onChange(selectedRowKeys.join(','), [...selectedRows]);
      },
    );
  };

  render() {
    const {
      inputDefaultValue = '',
      selectType = 'radio',
      rowKey = 'id',
      value,
      initNull,
      parentIds,
    } = this.props;
    const {
      selectNode,
      changeTree,
      visible,
      showValue,
      personData,
      selectedRows,
      selectedRowKeys,
      tablePagination,
      selectedData,
    } = this.state;

    const col: any = [
      {
        title: '序号',
        dataIndex: 'order',
        render(text: any, record: any, index: any) {
          return ++index;
        },
      },
      { title: '编号', dataIndex: 'code' },
      { title: '姓名', dataIndex: 'name' },
      { title: '公司', dataIndex: 'companyName' },
      // { title: '岗位', dataIndex: 'parentName' },
    ];
    const rowSelection: any = {
      type: selectType,
      onChange: this.handleRowSelect,
      selectedRowKeys,
      // selectedRows,
      // getCheckboxProps: (record: any) => ({
      //   disabled: !(record.type === 'EMPLOYEE'), // Column configuration not to be checked
      // }),
    };
    return (
      <>
        <div className='values__wrap'>
          {/* 初始化显示数据 */}
          {/* <Input value={showValue || inputDefaultValue} contentEditable={false} onClick={this.showModal} /> */}
          <Input contentEditable={false} onClick={this.showModal} />
          {selectedData && (
            <div className='values'>
              {selectedData.map((item: any, index: any) => (
                <Tag
                  onClick={this.showModal}
                  key={item.id}
                  closable
                  onClose={() => {
                    this.handleRmTag(index);
                  }}
                >
                  {item.name}
                </Tag>
              ))}
            </div>
          )}
        </div>
        <Modal
          title="人员选择"
          visible={visible}
          onCancel={this.hideModal}
          onOk={this.handleChange}
          destroyOnClose
          width={800}
          wrapClassName="org-emp-select-ctt"
          okButtonProps={{
            icon: <CheckOutlined />,
          }}
          cancelButtonProps={{
            icon: <RollbackOutlined />,
          }}
        >
          <div className="leftRight">
            <div className="left-tree" style={{ width: '224px' }}>
              <AsyncTree
                method={'GET'}
                needSearch={false}
                url='/sym/org/findListByParentCode'
                nodeInfo={selectNode}
                treeNodeClick={this.treeNodeClick}
                changeTree={changeTree}
                changeTreeData={this.changeTreeData}
              />
            </div>
            <div className="rightList">
              <Row className="search__content">
                <Row className="search__form__foot">
                  <Form
                    ref={this.formRef}
                  >
                    <Row>
                      <Col span={12}>
                        <Form.Item {...formItemLayout} label="编码" name="code">
                          <Input />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item {...formItemLayout} label="姓名" name="name">
                          <Input />
                        </Form.Item>
                      </Col>
                    </Row>
                  </Form>

                  <Row className="search__foot" type="flex" justify="end">
                    <Button icon={<SearchOutlined />} type="primary" onClick={this.handleSearch}>
                      查询
                    </Button>
                    <Button
                      style={{ marginLeft: 10 }}
                      icon={<UndoOutlined />}
                      onClick={() => this.formRef.current.resetFields()}
                    >
                      重置
                    </Button>
                  </Row>
                </Row>
              </Row>
              <Table
                bordered
                rowSelection={{
                  ...rowSelection,
                }}
                loading={this.state.listLoading}
                pagination={{
                  current: tablePagination.current,
                  pageSize: tablePagination.pageSize,
                  total: tablePagination.total,
                  onChange: this.handlePaginationChange,
                }}
                size="small"
                rowKey={rowKey}
                dataSource={personData}
                columns={col}
              />
            </div>
          </div>
        </Modal>
      </>
    );
  }
}

export default OrgEmpSelect
